<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm"  :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="文件名" prop="fileName">
        <el-input v-model="queryParams.fileName" placeholder="请输入文件名" clearable style="width: 240px"
                  @keyup.enter.native="handleQuery" />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search"  @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh"  @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="primary"-->
<!--          plain-->
<!--          icon="el-icon-plus"-->
<!--          -->
<!--          @click="handleAdd"-->
<!--          v-hasPermi="['system:yqCyxz:add']"-->
<!--        >新增</el-button>-->
<!--      </el-col>-->
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain icon="el-icon-upload2"

          @click="handleImport"
          v-hasPermi="['system:yqCyxz:upload']"
        >上传</el-button>
      </el-col>
      <el-col :span="1.5" v-if="isFbState">
        <el-select v-model="fileMJ" placeholder="请选择密级">
            <el-option v-for="dict in renyuanOptions" :key="dict.dictValue" :value="dict.dictValue" :label="dict.dictLabel"></el-option>
          </el-select>
      </el-col>
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="success"-->
<!--          plain-->
<!--          icon="el-icon-edit"-->
<!--          -->
<!--          :disabled="single"-->
<!--          @click="handleUpdate"-->
<!--          v-hasPermi="['system:yqcyxz:edit']"-->
<!--        >修改</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="danger"-->
<!--          plain-->
<!--          icon="el-icon-delete"-->
<!--          -->
<!--          :disabled="multiple"-->
<!--          @click="handleDelete"-->
<!--          v-hasPermi="['system:yqcyxz:remove']"-->
<!--        >删除</el-button>-->
<!--      </el-col>-->
<!--      <el-col :span="1.5">-->
<!--        <el-button-->
<!--          type="warning"-->
<!--          plain-->
<!--          icon="el-icon-download"-->
<!--          -->
<!--          @click="handleExport"-->
<!--          v-hasPermi="['system:yqcyxz:export']"-->
<!--        >导出</el-button>-->
<!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="yqcyxzList" @selection-change="handleSelectionChange" height="610">
      <el-table-column type="selection" width="55" align="center" />
      <el-table-column label="序号" type="index" :index="table_index" width="55" align="center" prop="id"/>
      <el-table-column label="文件名" align="center" prop="fileName" />
        <el-table-column label="密级"  v-if="isFbState" prop="" >
          <template slot-scope="scope">
                      <span v-for="(i, idx) in renyuanOptions" :key="idx">
                        {{ scope.row.mj == i.dictValue ? i.dictLabel : '' }}
                      </span>
          </template>
        </el-table-column>
      <el-table-column label="文件大小" align="center" prop="fileSize" />
<!--      <el-table-column label="文件路径" align="center" prop="filePath" />-->
<!--      <el-table-column label="上传人ID" align="center" prop="uploaderId" />-->
      <el-table-column label="上传人姓名" align="center" prop="uploaderName" />
<!--      <el-table-column label="发布范围" align="center" prop="releaseScope" />-->
<!--      <el-table-column label="发布时间" align="center" prop="releaseTime" />-->
<!--      <el-table-column label="是否已发布" align="center" prop="isRelease" />-->
<!--      <el-table-column label="创建人ID" align="center" prop="creatorId" />-->
<!--      <el-table-column label="创建时间" align="center" prop="createTime" />-->
<!--      <el-table-column label="最后修改人" align="center" prop="LASTUPDATER" />-->
<!--      <el-table-column label="最后修改时间" align="center" prop="lastupdateTime" />-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
<!--        <template slot-scope="scope">-->
<!--          <el-button-->
<!--            -->
<!--            type="text"-->
<!--            icon="el-icon-upload"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:yqCyxz:release']"-->
<!--          >发布</el-button>-->
<!--          <el-button-->
<!--            -->
<!--            type="text"-->
<!--            icon="el-icon-refresh-left"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:yqCyxz:disRelease']"-->
<!--          >取消发布</el-button>-->
<!--          <el-button-->
<!--            -->
<!--            type="text"-->
<!--            icon="el-icon-download"-->
<!--            @click="handleDownload(scope.row)"-->
<!--            v-hasPermi="['system:yqCyxz:download']"-->
<!--          >下载</el-button>-->
<!--          <el-button-->
<!--            -->
<!--            type="text"-->
<!--            icon="el-icon-delete"-->
<!--            @click="handleDelete(scope.row)"-->
<!--            v-hasPermi="['system:yqCyxz:remove']"-->
<!--          >删除</el-button>-->
<!--        </template>-->
        <template slot-scope="scope">

          <el-button
            v-if="scope.row.uploaderId === scope.row.userId && scope.row.isRelease === 0"

            type="text"
            icon="el-icon-upload"
            @click="handleRelease(scope.row)"
            v-hasPermi="['system:dept:list']"
          >
            发布
          </el-button>

          <el-button
            v-if="scope.row.uploaderId === scope.row.userId && scope.row.isRelease === 1"

            type="text"
            icon="el-icon-refresh-left"
            @click="handleDisRelease(scope.row)"
            v-hasPermi="['system:yqCyxz:disRelease']"
          >
            取消发布
          </el-button>

          <el-button

            type="text"
            icon="el-icon-download"
            @click="handleDownload(scope.row)"
            v-hasPermi="['system:yqCyxz:download']"
          >下载</el-button>

          <el-button
            v-if="scope.row.uploaderId === scope.row.userId"

            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['system:yqCyxz:remove']"
          >
            删除
          </el-button>

        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改常用下载对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="80px">
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 上传文件对话框 -->
    <el-dialog :title="upload.title" :visible.sync="upload.open" width="400px" append-to-body @close="handleCloseUploadDialog">
      <el-upload ref="upload" :limit="1" accept=".xlsx, .xls, .doc, .docx, .pdf, .ofd, .png, .jpg, jpeg" :headers="upload.headers"
                 :action="upload.url + '?updateSupport=' + upload.updateSupport+'&mj='+this.fileMJ" :disabled="upload.isUploading"
                 :on-progress="handleFileUploadProgress" :on-success="handleFileSuccess" :auto-upload="false" drag>
        <i class="el-icon-upload"></i>
        <div class="el-upload__text">将文件拖到此处，或<em>点击上传</em></div>
        <div class="el-upload__tip text-center" slot="tip">
          <!--          <div class="el-upload__tip" slot="tip">-->
          <!--            <el-checkbox v-model="upload.updateSupport" /> 重复数据是否更新-->
          <!--          </div>-->
<!--          <span>仅允许导入xls、xlsx格式文件。</span>-->
<!--          <el-link type="primary" :underline="false" style="font-size:12px;vertical-align: baseline;"-->
<!--                   @click="importTemplate">下载模板</el-link>-->
        </div>
      </el-upload>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitFileForm">确 定</el-button>
        <el-button @click="handleCloseUploadDialog">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 发布对话框 -->
    <el-dialog
      title="选择发布部门"
      :visible.sync="dialogVisible"
    >

      <el-checkbox-group
        v-model="checkedDeptIds"
      >

        <el-checkbox
          v-for="dept in deptList"
          :label="dept.deptId"
          :key="dept.deptId"
        >
          {{ dept.deptName }}
        </el-checkbox>

      </el-checkbox-group>

      <span slot="footer" class="dialog-footer">
  <el-button @click="dialogVisible = false">取 消</el-button>
  <el-button type="primary" @click="handleReleaseConfirm">确 定</el-button>
  </span>

    </el-dialog>

  </div>
</template>

<script>
import {
  listYqcyxz,
  getYqcyxz,
  delYqcyxz,
  addYqcyxz,
  updateYqcyxz,
  downloadYqcyxz,
  release,
  disRelease
} from "@/api/system/yqCyxz";
import {listDept} from "@/api/system/dept";
import {getToken} from "@/utils/auth";
import {download} from "@/utils/request";
import { getDicts_archive } from '@/api/archive/dict/dictManageData'
import { fbstat } from "@/api/archive/fileCollection/offlinReception.js";
import {
  getdamjbyrymj
} from "@/api/archive/fileCollection/offlinReception.js";
export default {
  name: "Yqcyxz",
  data() {
    return {
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      fileNames: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 常用下载表格数据
      yqcyxzList: [],
      // 部门数据
      deptList: [],
      checkedDeptIds: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      dialogVisible: false,
      upload: {
        // 是否显示弹出层（用户导入）
        open: false,
        // 弹出层标题（用户导入）
        title: "",
        // 是否禁用上传
        isUploading: false,
        // 是否更新已经存在的基础数据
        updateSupport: 0,
        // 设置上传的请求头部
        headers: { Authorization: "Bearer " + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + "/system/yqCyxz/upload"
      },
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        fileName: null,
        fileSize: null,
        filePath: null,
        uploaderId: null,
        uploaderName: null,
        releaseScope: null,
        releaseTime: null,
        isRelease: null,
        creatorId: null,
        createTime: null,
        LASTUPDATER: null,
        lastupdateTime: null,
        IDs: null
      },
      // downloadParams: {
      //   IDs:null
      // },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
      },
      renyuanOptions:[],
      fileMJ:undefined,
      isFbState:false
    };
  },
  created() {
    this.getList();
    fbstat().then(res => {  //false=不是分保，true=是分保
      this.isFbState = res.data
      if (this.isFbState) {
        //密级下拉列表
        getDicts_archive("MJ").then(res => { //人员密级
          getdamjbyrymj().then(resdata => { //此接口没有返回dictLabel，需要组装接口
            console.log(resdata, "------------------------")
            var mjdata = [];
            for (var i in resdata.data) {
              for (var j in res.data) {
                if (resdata.data[i].daMj == res.data[j].dictValue) {
                  mjdata.push(res.data[j])
                }
              }
            }

            this.renyuanOptions = mjdata
            console.log(this.renyuanOptions, "------------------------------------------")

          })
        })
      }
    })
  },
  methods: {
    table_index(index){
      return (this.queryParams.pageNum-1) * this.queryParams.pageSize + index + 1;
    },
    /** 查询常用下载列表 */
    getList() {
      // this.loading = true;

      listYqcyxz(this.queryParams).then(response => {
        this.yqcyxzList = response.rows;

        this.yqcyxzList.forEach(item => {
          let fileSize = parseInt(item.fileSize);
          let fileSizeMB = fileSize / 1024 / 1024;
          fileSizeMB = fileSizeMB.toFixed(3);
          let fileSizeStr = fileSizeMB + 'MB';
          item.fileSize = fileSizeStr;
        });

        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        ID: null,
        fileName: null,
        fileSize: null,
        filePath: null,
        uploaderId: null,
        uploaderName: null,
        userId: null,
        releaseScope: null,
        releaseTime: null,
        isRelease: null,
        creatorId: null,
        createTime: null,
        LASTUPDATER: null,
        lastupdateTime: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.ID)
      this.single = selection.length!==1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    // handleAdd() {
    //   this.reset();
    //   this.open = true;
    //   this.title = "添加常用下载";
    // },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const ID = row.ID || this.ids
      getYqcyxz(ID).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改常用下载";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.ID != null) {
            updateYqcyxz(this.form).then(response => {
              this.$modal.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addYqcyxz(this.form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }
        }
      });
    },
    /** 下载按钮操作 */
    handleDownload(row) {
      const IDs = row.id || this.ids;
      const fileName = row.fileName || this.fileNames;
      this.queryParams.IDs = IDs;
      let downloadParams = {
        IDs:IDs,
        sydm:"changyongxiazai"
      }
      this.$modal.confirm('是否确认下载文件名为"' + fileName + '"的文件？').then(function() {
        return download('/system/yqCyxz/download',{
            ...downloadParams
          },row.fileName);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("下载成功！");
      }).catch(() => {});
    },
    // async handleDownload(row) {
    //
    //   try {
    //
    //     // 获取ID和文件名
    //     const ids = row.id || this.ids;
    //     const fileName = row.fileName || '';
    //
    //     // 调用下载接口
    //     console.log('Calling download API...');
    //     const response = await downloadYqcyxz(ids);
    //     console.log('API response:', response);
    //
    //     // 获取文件数据
    //     console.log('Getting file data...');
    //     const blob = new Blob([response.data], {
    //       type: response.headers['content-type']
    //     });
    //     console.log('File blob created');
    //
    //     // 创建下载链接
    //     console.log('Creating download link...');
    //     const link = document.createElement('a');
    //     link.href = URL.createObjectURL(blob);
    //     link.download = fileName;
    //     console.log('Link created');
    //
    //     // 触发下载
    //     console.log('Triggering download...');
    //     document.body.appendChild(link);
    //     link.click();
    //     document.body.removeChild(link);
    //     console.log('Download triggered');
    //
    //     // 成功提示
    //     this.$message.success('Download succeeded');
    //
    //   } catch (error) {
    //
    //     console.error('Download failed:', error);
    //
    //     // 失败提示
    //     this.$message.error('Download failed');
    //
    //   } finally {
    //
    //     console.log('Download process completed');
    //
    //   }
    //
    // },
    /** 删除按钮操作 */
    handleDelete(row) {
      const IDs = row.id || this.ids;
      const fileName = row.fileName || this.fileNames;
      console.log(row,"0000000000000")
      if(row.isRelease == '1') {

        this.$modal.confirm(
          '该文件已发布,请先取消发布后再操作'
        ).then(() => {
          // 用户确认后返回
        });

        return;

      }
      this.$modal.confirm('是否确认删除文件名为"' + fileName + '"的文件？').then(function() {
        return delYqcyxz(IDs);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 发布按钮操作 */
    handleRelease(row) {
      this.row = row;
      listDept().then(res => {
        // 获取部门数据
        if (res.data.slice(2)!=""){
          this.deptList = res.data.slice(2);
        }else {
          this.deptList = res.data.slice(0);
        }
        // 打开弹窗
        this.dialogVisible = true;
      })
    },
    /** 确认发布按钮 */
    handleReleaseConfirm() {
      // 拼接选中部门key
      let releaseScope = '';
      this.checkedDeptIds.forEach(id => {
        releaseScope += id + ',';
      });
      releaseScope = releaseScope.slice(0, -1); // 去除最后一个逗号
      if (releaseScope==''){
        this.$modal.msgWarning("请选择部门！");
      }else {
        this.row.releaseScope=releaseScope;
        console.log(this.row,"000000000000000000");
        // // 调用接口
        // this.release({
        //   id: this.row.id,
        //   releaseScope
        // }).then(() => {
        //   // 发布成功处理
        // })
        // const fileName = this.row.fileName;
        // this.$modal.confirm('是否确认发布文件名为"' + fileName + '"的文件？').then(function() {
        //   return release(this.row);
        // }).then(() => {
        //   this.getList();
        //   this.$modal.msgSuccess("发布成功！");
        //   this.dialogVisible = false;
        // }).catch(() => {});

        release(this.row).then(() => {
          this.row = null;
          this.checkedDeptIds = [];
          this.getList();
          this.$modal.msgSuccess("发布成功！");
          this.dialogVisible = false;
        })
        // this.getList();
        // this.dialogVisible = false;
      }

    },
    /** 取消发布按钮操作 */
    handleDisRelease(row) {
      const IDs = row.id || this.ids;
      const fileName = row.fileName || this.fileNames;
      this.$modal.confirm('是否确认取消发布文件名为"' + fileName + '"的文件？').then(function() {
        return disRelease(row);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("取消成功！");
      }).catch(() => {});
    },
    /** 导出按钮操作 */
    // handleExport() {
    //   this.download('system/yqcyxz/export', {
    //     ...this.queryParams
    //   }, `yqcyxz_${new Date().getTime()}.xlsx`)
    // },
    /**上传按钮操作 */
    handleImport() {
      if(this.isFbState){
        if (this.fileMJ == undefined) {
                this.$message.warning(`请选择密级`);
                return false
            }
      }

      this.upload.title = "上传文件";
      this.upload.open = true;
    },
    // 文件上传中处理
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true;
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.open = false;
      this.upload.isUploading = false;
      this.$refs.upload.clearFiles();
      this.$alert("<div style='overflow: auto;overflow-x: hidden;max-height: 70vh;padding: 10px 20px 0;'>" + response.msg + "</div>", "上传结果", { dangerouslyUseHTMLString: true });
      this.getList();
    },
    // 提交上传文件
    submitFileForm() {
      this.$refs.upload.submit();
    },
    handleCloseUploadDialog() {
      this.$refs.upload.clearFiles();
      this.upload.open = false;
    }
  }
};
</script>
